package com.timguan.render.web.common;

import com.timguan.render.service.common.B2CMallServiceConfig;
import com.timguan.common.cache.common.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by guankaiqiang on 2014/12/1.
 */
public class GlobalMethodHandlerExeptionResolver implements HandlerExceptionResolver, Ordered {
    private static final Logger logger = LoggerFactory.getLogger(GlobalMethodHandlerExeptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.error("逻辑漏洞，出现未捕获异常!", ex);
        request.setAttribute(Constants.DISASTER_RECOVERY_FLAGNAME, "1");
        try {
            if (!response.isCommitted()) {
                response.sendRedirect(B2CMallServiceConfig.getInstance().getPageNotFoundSite());
            }
        } catch (IOException e) {
            logger.error("redirect failed!", e);
        }
        //modelAndView为空,spring认为异常未被处理，会一直向外层抛出，使用GlobalResolver的好处是后面可以加通用异常的处理逻辑；
        return new ModelAndView();
    }

    private int order = Integer.MAX_VALUE;

    @Override
    public int getOrder() {
        return this.order;
    }

    public void setOrder(int order) {
        this.order = order;
    }
}
